package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.R;
import com.itheima.reggie.service.CommonService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Service
public class CommonServiceImpl  implements CommonService {
 @Value("${reggie.path}")
 private String basePath;

 @Override
 public void download(String name, HttpServletResponse response) {
  try {
   //输入流读取文件内容
   FileInputStream fis = new FileInputStream(new File(basePath + name));
   //输出流，通过输出流将读取到得文件写回浏览器，在浏览器展示图片
   ServletOutputStream outputStream = response.getOutputStream();
   response.setContentType("image/jpeg");
   int len = 0;
   byte[] bytes = new byte[1024];
   while ((len = fis.read(bytes)) != -1) {
    outputStream.write(bytes, 0, len);
    outputStream.flush();
   }
   outputStream.close();
   fis.close();

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 @Override
 public String upLoad(MultipartFile file) {
  String originalFilename = file.getOriginalFilename();
  String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
  String fileName = UUID.randomUUID().toString() + suffix;

  File dir = new File(basePath);
  if (!dir.exists()) {
   dir.mkdirs();
  }

  try {
   file.transferTo(new File(basePath + fileName));
  } catch (IOException e) {
   e.printStackTrace();
  }
  return fileName;
 }
}
